package com.tool.weixin.api;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;

import com.tool.weixin.model.Wxuser;
import com.tool.weixin.util.HttpUtils;
/**
 * 用户
 * @author huff
 *
 */
public class UserApi {
	
	private static final Logger logger = org.slf4j.LoggerFactory.getLogger(UserApi.class);
	/**关注用户获得信息**/
	private static final String user_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
	/**网页授权获得用户信息**/
	private static final String user_url_oauth = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
	/**
	 * 获得用户openid(网页授权)
	 * @return
	 */
	public static Wxuser getUserInfo(String accesstoken,String openid){
		logger.debug("网页授权获得用户信息");
		return getUserInfo(user_url_oauth,accesstoken, openid);
	}
	/**
	 * 获得用户openid(关注用户)
	 * @param appid
	 * @param appsecret
	 * @param code
	 * @return
	 */
	public static Wxuser getUserInfo(String openid) {
		return getUserInfo(user_url, AccessTokenApi.getAccessToken().getToken(), openid);
	}
	
	/**
	 * 获得用户openid
	 * @param appid
	 * @param appsecret
	 * @param code
	 * @return
	 */
	private static Wxuser getUserInfo(String url,String accesstoken,String openid){
		if(StringUtils.isEmpty(openid)) return null;
		String requestUrl = url.replace("ACCESS_TOKEN", accesstoken).replace("OPENID", openid);
		JSONObject jsonObject = HttpUtils.httpRequest(requestUrl, "GET", null);
		Wxuser wxuser = null;
		if(null != jsonObject){
			try {
				logger.debug(jsonObject.toString());
				wxuser = new Wxuser();
				wxuser.setOpenid(jsonObject.getString("openid"));
				if(jsonObject.containsKey("subscribe")) {
					wxuser.setSubscribe(jsonObject.getInt("subscribe"));
				}
				if(jsonObject.containsKey("headimgurl")) {
					wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
				}
				if(jsonObject.containsKey("nickname")) {
					wxuser.setNickname(jsonObject.getString("nickname"));
				}
				if(jsonObject.containsKey("unionid")) {
					wxuser.setUnionid(jsonObject.getString("unionid"));
				}
				if(jsonObject.containsKey("sex")) {
					wxuser.setSex(jsonObject.getString("sex"));
				} else {
					wxuser.setSex("0");
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("获取微信用户信息失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
			}
		}
		return wxuser;
	}
}
